package com.future.baselib.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.future.baselib.R;
import com.future.baselib.entity.BaseResponse;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.http.HttpRequest;
import com.google.gson.Gson;

import java.lang.reflect.Type;
import java.util.List;
import java.util.TreeMap;

/**
 * @author jniu
 * @Email niuxiaoqi@hztianque.com
 * @time 2018/11/15
 */
public abstract class BaseListFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnItemClickListener {

    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerView;

    protected BaseQuickAdapter adapter;

    private boolean isLoading = false;
    private int page = 0;
    private int pageSize = 20;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater,container,savedInstanceState);
        refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(this);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(getLayoutManager());
        adapter = getAdapter();
        recyclerView.setAdapter(adapter);
        adapter.setEmptyView(getEmptyView());
        adapter.setOnLoadMoreListener(this, recyclerView);
        adapter.disableLoadMoreIfNotFullPage(recyclerView);
        adapter.setEnableLoadMore(false);
        adapter.setOnItemClickListener(this);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        requestData();
    }

    @Nullable
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_base_list;
    }

    protected RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(getContext());
    }

    protected View getEmptyView() {
        return LayoutInflater.from(getContext()).inflate(getEmptyViewId(), null);
    }

    protected int getEmptyViewId() {
        return R.layout.layout_empty_view_default;
    }

    protected abstract BaseQuickAdapter getAdapter();

    @Override
    public void onRefresh() {
        page = 0;
        requestData();
    }

    private void requestData() {
        isLoading = true;
        new HttpRequest()
                .with(getContext())
                .setPath(getPath())
                .addParam("p", page++)
                .addParam("size", pageSize)
                .addParams(getRequestParams())
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        isLoading = false;
                        Object o = new Gson().fromJson(response.data, getTypeToken());
                        if (o instanceof List) {
                            List list = (List) o;
                            if (page == 1) {
                                adapter.setNewData(list);
                                refreshLayout.setRefreshing(false);
                            } else {
                                adapter.addData(list);
                                if (list == null || list.size() == 0) {
                                    adapter.loadMoreEnd(true);
                                    return;
                                }
                                adapter.loadMoreComplete();
                            }

                        } else {
                            LogUtils.e("数据格式异常");
                        }
                    }
                })
                .addFailListener(new HttpRequest.OnNetworkFail() {
                    @Override
                    public void onFail(String message) {
                        isLoading = false;
                        if (page == 1) {
                            refreshLayout.setRefreshing(false);
                        } else {
                            adapter.loadMoreFail();
                        }
                        page--;
                    }
                }).start(getResponse());
    }

    protected abstract Type getTypeToken();

    private BaseResponse getResponse() {
        return new DefaultResponse();
    }

    protected abstract TreeMap<String, String> getRequestParams();
    protected abstract String getPath();

    @Override
    public void onLoadMoreRequested() {
        if (isLoading()) {
            adapter.loadMoreEnd();
            return;
        }
        requestData();
    }

    protected boolean isLoading() {
        return isLoading || refreshLayout.isRefreshing();
    }
}
